<?php
namespace app\common\model;

use org\util\TreeUtil;
use think\Db;
use think\helper\Str;

class UserModel extends BaseModel
{

    protected $name = 'user'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改
    //类型自动转换
    protected $type = [];
    /*读取器*/

    /*修改器*/
    protected function setPasswordAttr($value)
    {
        return md5($value);
    }

    /**
     * 获取用户资料
     * @param $utype
     * @param $uid
     */
    public function getInfo($utype, $uid)
    {
        $sql    = "select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='" . config('database.database') . "' and TABLE_NAME='user_" . Str::snake($utype) . "'";
        $expand = Db::query($sql);
        if (empty($expand)) { //没有扩展表
            $info = Db::table('user')->where('uid', $uid)->find();
        } else {
            $expandTable = Str::snake($expand[0]['TABLE_NAME']);
            $info        = Db::table('user')->where('uid', $uid)->find();
            $expandInfo  = Db::table($expandTable)->field('uid', true)->where('uid', $uid)->find();
            if ($expandTable=='user_site'){
                $expandInfo['site_config']=json_decode($expandInfo['site_config'],true);
            }
            $info        = array_merge($info, $expandInfo);
        }
        if (empty($info['headimgurl'])){
            $webConfig=cache('webconfig0');
            $info['headimgurl']=$webConfig['NOPIC'];
        }
        return $info;
    }

    /**
     * 获取关联会员模型
     * @param $utype
     * @return $this|\think\db\Query
     */
    public function getListModel($utype)
    {
        $sql    = "select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='" . config('database.database') . "' and TABLE_NAME='user_" . Str::snake($utype) . "'";
        $expand = Db::query($sql);
        if (empty($expand)) {
            $model = Db::table('user');
        } else { //关联扩展表
            $expandTable = Str::snake($expand[0]['TABLE_NAME']);
            $fields      = [
                'User'        => 'uid,utype,username,name,status,create_time,login_times,last_login_ip,last_login_time',
                'user_member' => 'openid,alias,sex,headimgurl,birthday,user_money,prepare_money,pay_points,prepare_points,parent_id',
                'user_site'   => 'site_name,company_name,grade_id,site_tel,site_image,prov_id,city_id,dist_id,area_name,address,site_recommend,site_status,site_sort,lat,lng,geohash',
            ];
            $model       = Db::view('user', $fields['User'])
                ->view($expandTable, $fields[$expandTable], $expandTable . '.uid=user.uid');
        }
        return $model;
    }

    /**
     * 添加用户
     * @param $data
     * @return bool
     */
    public function addData($data)
    {
        if ($this->where('username', $data['username'])->where('site_id',$data['site_id'])->where('utype', $data['utype'])->find()) {
            $this->error = '该用户已存在！';
            return false;
        }
        $this->isUpdate(false)->allowField(true)->save($data);
        $uid      = $this->getData('uid');
        $objModel = '\\app\\common\\model\\User' . Str::studly($this->getData('utype')) . 'Model';
        if (class_exists($objModel)) {
            $expandModel = new $objModel;
            $data['uid'] = $uid;
            $expandModel->addData($data);
        }
        return true;
    }

    /**
     * 编辑用户
     * @param $data
     * @return bool
     */
    public function editData($data)
    {
        if (empty($data['password'])) {
            unset($data['password']);
        }
        $info = $this->get($data['uid']);
        if ($info['username'] != $data['username']) {
            if ($this->where('username', $data['username'])->where('utype', $data['utype'])->find()) {
                $this->error = '该用户名已使用!';
                return false;
            }
        }
        if ($info['uid'] == 1) $data['status'] = 1; //系统管理员不允许禁用
        $this->isUpdate(true)->allowField(true)->save($data);
        $objModel = '\\app\\common\\model\\User' . Str::studly($info['utype']) . 'Model';
        if (class_exists($objModel)) {
            $expandModel = new $objModel;
            $expandModel->isUpdate(true)->allowField(true)->save($data,['uid'=>$info['uid']]);
        }
        return true;
    }

    /**
     * 删除
     * @param $uid
     * @return bool
     */
    public function delData($uid)
    {
        if ($uid == 1) {
            $this->error = '系统管理员不允许删除';
            return false;
        }
        $userinfo = $this->find($uid);
        $objModel = '\\app\\common\\model\\User' . Str::studly($userinfo->getData('utype')) . 'Model';
        if (class_exists($objModel)) { //删除扩展信息
            $expandModel = new $objModel;
            $expandModel->destroy($uid);
        }
        $this->destroy($uid);
        return true;
    }

    /**
     * 检测用户登录
     * @param $username
     * @param $password
     * @return bool
     */
    public function checkLogin($username, $password, $utype = 'system')
    {
        $user = $this->where('utype', $utype)->where('username', $username)->find();
        if (empty($user)) {
            $this->error = '用户不存在！';
            return false;
        }
        if ($user->getData('password') == md5($password)) {
            $status = $user->getData('status');
            $uid    = $user->getData('uid');
            if ($status == 1) {
                $groupId = $user->getData('group_id');   //获取权限信息
                if ($groupId == 0) {
                    $this->error = '该用户还未授权！';
                    return false;
                }
                $loginData = [
                    'last_login_time' => time(),
                    'last_login_ip'   => get_client_ip(),
                    'login_times'     => $user->getData('login_times') + 1,
                ];
                $this->where('uid', $uid)->update($loginData);
                return $uid;
            }
            $this->error = '该用户已锁定';
            return false;
        }
        $this->error = '密码输入错误！';
        return false;
    }

    /**
     * 获取用户权限
     * @param $uid
     * @param $utype
     * @return array
     */
    public function getMyRuleList($groupId,$utype){
        $ruleList = cache('auth_rule_'.$utype);
        if (empty($ruleList)){
            $model=new AuthRuleModel();
            $model->updateCache($utype);
            $ruleList = cache('auth_rule_'.$utype);
        }
        $authGroupModel = new AuthGroupModel();
        $rules = $authGroupModel->where('group_id',$groupId)->where('status',1)->value('rules');
        if(empty($rules)){
            return [];
        }
        if($rules!='all'){
            foreach($ruleList as $k=>$v){
                if(in_array($k,explode(',',$rules))){
                    $myRuleList[$k] = $v;
                }
            }
        }else{
            $myRuleList=$ruleList;
        }
        $treeRule = TreeUtil::channelLevel($myRuleList, 0, "&nbsp;", 'rule_id', 'rule_pid');
        return $treeRule;
    }

    /**
     * 获取用户投稿CMS栏目
     */
    public function getCmsCategory($siteId,$groupId){
        $category = cache('cms_category'.$siteId);
        $authGroupModel = new AuthGroupModel();
        $cmsCids = $authGroupModel->where('group_id',$groupId)->where('status',1)->value('cms_cids');
        if(empty($cmsCids)){
            return [];
        }
        if($cmsCids!='all'){
            foreach($category as $k=>$v){
                if(in_array($k,explode(',',$cmsCids))){
                    $result[$k] = $v;
                }
            }
        }else{
            $result=$category;
        }
        return $result;
    }
    /**
     * 获取用户投稿商品栏目
     */
    public function getGoodsCategory($siteId,$groupId){
        $category = cache('goods_category'.$siteId);
        $authGroupModel = new AuthGroupModel();
        $goodsCids = $authGroupModel->where('group_id',$groupId)->where('status',1)->value('goods_cids');
        if(empty($goodsCids)){
            return [];
        }
        if($goodsCids!='all'){
            foreach($category as $k=>$v){
                if(in_array($k,explode(',',$goodsCids))){
                    $result[$k] = $v;
                }
            }
        }else{
            $result=$category;
        }
        return $result;
    }
}
